package com.wl.login.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wl.bean.Result;
import com.wl.login.bean.LoginProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    LoginProperties properties;
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object myinfo = session.getAttribute(properties.getSessionKey());
        if (myinfo == null) {
            String accept = request.getHeader("Accept");
            if (accept.startsWith("application/json")) {
                // 如果是ajax请求, 返回result, 提示未登录
                Result result = new Result(0,"请先登录系统", null);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(objectMapper.writeValueAsString(result));
            } else {
                // cart.html?id=2,  requestURI=>cart.html,  queryString=>id=2
                // 获取访问的页面地址
                String requestURI = request.getRequestURI();
                String queryString = request.getQueryString();
                String path = requestURI;
                if(queryString != null){
                    path = path + "?" + queryString;
                }
                session.setAttribute("goto", path);
                // 如果是表单请求(xxx.html) 跳转到登录页
                response.sendRedirect("/login.html?cause=nologin");
            }
            return false;
        }
        return true;
    }

}
